import { useState, useCallback } from 'react';
import { getMenuList } from './api';
import {getFlatMenuList, toTree} from './utils'
import { useEffect } from 'react';
import routes from '@/config/routes';
const flatRoutes:Record<string,any> = getFlatMenuList(routes)
import { RouteObject } from "react-router-dom";
import { isNil } from 'lodash-es';

export default () => {
  const [menuList, setMenuList] = useState<any[]>([]);
  const [routes, setRoutes] = useState<RouteObject[]>([]);
  const [menuMap, setMenuMap] = useState<Record<string, any>>({});
  const [menuMapId, setMenuMapId] = useState<Record<string,any>>({});
  const [loading, setLoading] = useState<boolean>(false);
  const getMenuListRequest = useCallback(async () => {
    const { code, data } = await getMenuList()
    if (code === 0 && data?.length) {
      const routes:RouteObject[] = []
      const menuMap: Record<string, any> = {}
      const menuMapId:Record<string,any> = {}
      const menuList:Array<any>=[]
      data?.forEach((item:any) => {
        const router=item?.router
        if (flatRoutes?.[router]) {
            routes.push(flatRoutes?.[router])
         }
        if (router) {
          menuMap[router] = item
        }
     
        if (!isNil(item?.id)) {
          menuMapId[item?.id]=item
        }
        if (item?.hide===2) {
          menuList.push({
            ...item,
            key:item?.id
          })
        }
      });
      console.log("routes",routes)
      setRoutes(routes)
      setMenuMapId(menuMapId)
      setMenuList(toTree(menuList))
      setMenuMap(menuMap)
    }
  }, [])
  useEffect(() => {
    getMenuListRequest()
  },[getMenuListRequest])
  return {loading,menuList,routes,menuMap,menuMapId};
};
